package com.seguriapp.base;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.google.common.base.Preconditions;

/**
 * Provides a generic default implementation using Hibernate.
 * <p>
 * Subclasses should provide the Hibernate Session injected and the managed
 * Entity class (e.g. Article) in the constructor.
 * 
 * @author Tania Gonzales(taniadgv@gmail.com)
 */
public class GenericDaoImpl<T extends BaseEntity> implements GenericDao<T> {

  @Autowired
  private SessionFactory sessionFactory;

  private Class<T> entityClass;

  /**
   * Construct an instance of {@link GenericDaoImpl} with a Hibernate session
   * and the class of the entity this DAO manages.
   * 
   * @param session
   *          The Hibernate session.
   * @param entityClass
   *          The entity's class.
   */
  public GenericDaoImpl(Class<T> entityClass) {
    this.entityClass = entityClass;
  }

  protected Session getSession() {
    return sessionFactory.getCurrentSession();
  }

  public void delete(T entidad) {
    Preconditions.checkNotNull(entidad);
    getSession().delete(entidad);
  }

  public void save(T entidad) {
    Preconditions.checkNotNull(entidad);
    getSession().saveOrUpdate(entidad);
  }

  @SuppressWarnings("unchecked")
  public T findById(Long id) {
    return (T) getSession().load(entityClass, id);
  }

  @SuppressWarnings("unchecked")
  public List<T> list() {
    return getSession().createCriteria(entityClass).list();
  }

  public void setSessionFactoryBean(SessionFactory sessionFactory) {
    this.sessionFactory = sessionFactory;
  }
}
